package com.astrocsr.dao;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.astrocsr.common.db.SearchQueryTemplate;
import com.astrocsr.domain.bean.TblCSRLog;
import com.astrocsr.domain.condition.CSRLogCondition;
import com.astrocsr.domain.db.PagingInfo;
import com.astrocsr.domain.db.SearchResult;

@Repository("csrLogDAO")
public class CSRLogDAO extends BaseHelperDAO {
   
	public void addAuditlog(TblCSRLog entity) {
		// Insert to database
		getCurrentSession().save(entity);
	}
	
	public void updateAuditlog(TblCSRLog entity) {
		// Insert to database
		getCurrentSession().update(entity); 
	}

	public SearchResult<TblCSRLog> listAuditLog(CSRLogCondition condition, PagingInfo pagingInfo) throws Exception {
		
		// Prepare
		SearchResult<TblCSRLog> result = null; 
		String orderColumn = " model.activityid desc";
		SearchQueryTemplate searchQueryTemplate = new SearchQueryTemplate(orderColumn, pagingInfo);
		searchQueryTemplate.setQueryString("FROM TblCSRLog model ");
		
		// Set condition (where statement, default logic operator is AND)
		if (condition != null) {
			if (condition.getStartDate() != null) {
				searchQueryTemplate.setExpression("model.activitydt >= :sActivitydt", "sActivitydt", condition.getStartDate());
			}
			if (condition.getEndDate() != null) {
				searchQueryTemplate.setExpression("model.activitydt <= :eActivitydt", "eActivitydt", condition.getEndDate());
			}
			if (StringUtils.isNotBlank(condition.getSearchuid())) {
				String searchuid = "%" + condition.getSearchuid() + "%";
				searchQueryTemplate.setExpression("model.userid like :searchuid", "searchuid", searchuid);
			}
			if (StringUtils.isNotBlank(condition.getActivityType())) {
				String activityType = condition.getActivityType();
				searchQueryTemplate.setExpression("model.activityType = :activityType", "activityType", activityType);
			}
			if (condition.getGroupCodeList() != null && !condition.getGroupCodeList().isEmpty()) {
				searchQueryTemplate.setExpression("model.role in (:groupCodeList)", "groupCodeList", condition.getGroupCodeList());
			}
		}

		// execute search with paging
		result = this.find(searchQueryTemplate);
		
		return result;
	}

}
